package mo.offer_special;

import java.util.*;

public class L113 {

    public int[] findOrder(int numCourses, int[][] prerequisites) {
        Map<Integer, List<Integer>> graph = new HashMap<>();
        int[] degree = new int[numCourses];
        for (int[] prerequire : prerequisites) {
            int start = prerequire[1];
            int end = prerequire[0];
            degree[end]++;
            List<Integer> target = graph.get(start);
            if (target == null) {
                target = new ArrayList<>();
                graph.put(start, target);
            }
            target.add(end);
        }

        Queue<Integer> queue = new ArrayDeque<>();
        for (int i = 0; i < numCourses; i++) {
            if (degree[i] == 0) {
                queue.offer(i);
            }
        }

        int[] ret = new int[numCourses];
        int idx = 0;
        while (!queue.isEmpty()) {
            int node = queue.poll();
            ret[idx++] = node;

            List<Integer> outs = graph.get(node);
            if (outs == null || outs.size() == 0) {
                continue;
            }

            for (int out : outs) {
                degree[out]--;
                if (degree[out] == 0) {
                    queue.offer(out);
                }
            }
        }

        return idx == numCourses ? ret : new int[0];
    }

}
